package com.bilin.coin;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bilin.coin.bean.BannerBean;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.UpDateMsgBean;
import com.bilin.coin.bean.VersionBean;
import com.bilin.coin.bean.WebUpDateUrlBackMsgBean;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.common.base.BaseFragment;
import com.bilin.coin.fragment.HomeFragment;
import com.bilin.coin.fragment.MillFragment;
import com.bilin.coin.fragment.MyFragment;
import com.bilin.coin.fragment.TaskFragment;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.callback.StringCallBack;
import com.bilin.coin.service.DownloadFileService;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.MPermissionUtils;
import com.bilin.coin.utils.MobilePhoneDeviceInfo;
import com.bilin.coin.widget.CustomViewPager;
import com.bilin.coin.widget.OngoingUpdateDialog;
import com.bilin.coin.widget.UpDateDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import kt.com.bilin.coin.ad.AdManager;
import kt.com.bilin.coin.utils.Logger;
import kt.com.bilin.coin.viewmodel.BackgroundCommonApi;


public class MainActivity extends BaseAppCompatActivity {


    @BindView(R.id.rg_main)
    RadioGroup rg_main;
    @BindView(R.id.rb_home)
    RadioButton rb_home;
    @BindView(R.id.rb_personal)
    RadioButton rb_personal;
    @BindView(R.id.rb_mill)
    RadioButton rb_mill;
    @BindView(R.id.rb_live)
    RadioButton rb_live;

    @BindView(R.id.viewPager)
    CustomViewPager viewPager;

    private boolean isKeycodeBack = true;

    private ArrayList<BaseFragment> mFragmentList;
    private int position = 0;
    VpAdapter vpAdapter;
    private List<BannerBean> bannerBeans;
    private UpDateDialog mUpDateDialog;
    private String strLink;
    private int type;

    @Override
    protected void initView() {
        checkPermissions();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AdManager.INSTANCE.showInner(this);
    }

    private void init() {
        initStatusBar();
        initFragment();
        viewPager.setPagingEnabled(false);
        viewPager.setOffscreenPageLimit(4);
        vpAdapter = new VpAdapter(getSupportFragmentManager());
        viewPager.setAdapter(vpAdapter);
        initListener();
        BackgroundCommonApi.notify("");
        AdManager.INSTANCE.init(this);
    }

    private void initStatusBar() {
        ImmersionBar.with(this)
                .statusBarView(R.id.view)
                .navigationBarColor(android.R.color.white)
                .autoDarkModeEnable(false, 0.2f)
                .init();
        ImmersionBar.with(MainActivity.this).statusBarDarkFont(false, 0.2f).init();
    }

    public void selectTab(int index) {
        rg_main.check(index);
    }

    //int oriPosition = 0;
    private void initListener() {
        rg_main.check(R.id.rb_home);
        rg_main.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //oriPosition = position;
                try {
                    switch (checkedId) {
                        case R.id.rb_home:
                            position = 0;
                            HomeFragment homeFragment = (HomeFragment) mFragmentList.get(0);
                            homeFragment.onRefresh();
                            break;
                        case R.id.rb_mill:
                            position = 1;
                            MillFragment millFragment = (MillFragment) mFragmentList.get(1);
                            millFragment.onRefresh();
                            break;
                        case R.id.rb_live:
                            position = 2;
                            TaskFragment taskFragment = (TaskFragment) mFragmentList.get(2);
                            taskFragment.onRefresh();
                            break;
                        case R.id.rb_personal:
                            position = 3;
                            MyFragment myFragment = (MyFragment) mFragmentList.get(3);
                            myFragment.onRefresh();
                            break;
                    }
                    viewPager.setCurrentItem(position);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                switch (position) {
                    case 0:
                        ImmersionBar.with(MainActivity.this).statusBarDarkFont(false, 0.2f).init();
                        break;
                    case 1:
                        ImmersionBar.with(MainActivity.this).statusBarDarkFont(true, 0.2f).init();
                        break;
                    case 2:
                        ImmersionBar.with(MainActivity.this).statusBarDarkFont(false, 0.2f).init();
                        break;
                    case 3:
                        ImmersionBar.with(MainActivity.this).statusBarDarkFont(false, 0.2f).init();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void initFragment() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new MillFragment());
        mFragmentList.add(new TaskFragment());
        mFragmentList.add(new MyFragment());
        //mFragmentList.add(new MyFragment());
    }

    public void switchTaskTab() {
        rb_live.performClick();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isKeycodeBack = true;
                }
            }, 2000);

            if (isKeycodeBack) {
                showToast("再按一次返回键退出应用");
                isKeycodeBack = false;
            } else {
                finish();
            }
        }
        return true;
    }

    class VpAdapter extends FragmentPagerAdapter {
        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return mFragmentList.get(i);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }

    @Override
    public boolean isShowToolBar() {
        return false;
    }

    private void checkVersion() {
        RequestUtils
                .post()
                .url("/api/params/version")
                .addParams("version", MobilePhoneDeviceInfo.getVersionName(this))
                .addParams("platform", "android")
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new StringCallBack<VersionBean>() {

                    @Override
                    public void onCallBackNext(VersionBean result) {

                        int status = result.getData().getStatus();

                        if (BuildConfig.DEBUG) {
                            status = 0;
                        }
                        //status = 1;
                        strLink = result.getData().getLink();
                        //strLink = "https://btcpb.net/download/BTCBP";
                        // 0 不需要更新     1 提醒用户更新     2强制更新
                        if (status == 0) {
                            //showToast("不需要更新");
                        } else if (status == 1) {
                            type = status;
                            mUpDateDialog = new UpDateDialog(MainActivity.this, R.style.Dialog, false, result.getData().getNewVersion(), result.getData().getContent(), "main");
                            mUpDateDialog.show();

                        } else if (status == 2) {
                            type = status;
                            mUpDateDialog = new UpDateDialog(MainActivity.this, R.style.Dialog, true, result.getData().getNewVersion(), result.getData().getContent(), "main");
                            mUpDateDialog.setOnKeyListener(keyListener);
                            mUpDateDialog.setCancelable(false);
                            mUpDateDialog.show();

                        }


                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        DialogUtils.dismissDialogLoading();
                        showMsg(e);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void WebUpDateUrlBackMsg(WebUpDateUrlBackMsgBean mWebUrlBackMsgBean) {
        boolean update = mWebUrlBackMsgBean.isUpdate();
        if (update) {
            String url = mWebUrlBackMsgBean.getUrl();
            if (type == 1) {
                showToast(getString(R.string.start_download_ing));
                Intent itDownloadFile = new Intent(MainActivity.this, DownloadFileService.class);
                itDownloadFile.putExtra("url", url);
                startService(itDownloadFile);
                mUpDateDialog.dismiss();
            } else {
                mUpDateDialog.dismiss();
                OngoingUpdateDialog updateDialog = new OngoingUpdateDialog(MainActivity.this, R.style.Dialog, url);
                updateDialog.setCancelable(false);
                updateDialog.show();
            }

        }
        EventBus.getDefault().removeStickyEvent(mWebUrlBackMsgBean);
    }


    /**
     * 检查权限
     */
    private void checkPermissions() {
        String permission[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        MPermissionUtils.requestPermissionsResult(this, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                init();
                checkVersion();
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(MainActivity.this);
            }
        }, permission);
    }

    /**
     * 更新的对话框回传
     *
     * @param upDateMsgBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UpDateMsg(UpDateMsgBean upDateMsgBean) {
        boolean isUpDateMsg = upDateMsgBean.ismUpDateMsg();
        boolean ismMianAndSet = upDateMsgBean.ismMianAndSet();
        if (ismMianAndSet) {
            if (isUpDateMsg) {

                String permission[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                MPermissionUtils.requestPermissionsResult(this, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {

                        baseStartActivityWith("/common/WebLoadingUpdateActivity")
                                .withString("mMianAndSet", "main")
                                .withString("strUrl", strLink)
                                .navigation();

                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(MainActivity.this);
                    }
                }, permission);

                //mUpDateDialog.dismiss();

            } else {
                mUpDateDialog.dismiss();

            }
        }
        EventBus.getDefault().removeStickyEvent(upDateMsgBean);
    }


    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                if (mUpDateDialog.isShowing()) {
                    mUpDateDialog.dismiss();
                }
                finish();
                return true;
            } else {
                return false;
            }
        }
    };


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void switchTab(CommonSuccessEvent switchTabEvent) {
        //rg_main.check(R.id.rb_home);
        if (switchTabEvent.getType() == CommonSuccessEvent.SwitchTab) {
            rb_home.performClick();
        }
        EventBus.getDefault().removeStickyEvent(switchTabEvent);
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        //super.onSaveInstanceState(outState, outPersistentState);
    }
}